package top.milkbox.core.handler.mybatisPlus;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotWebContextException;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import top.milkbox.common.enums.CommonDeleteFlagEnum;

import java.util.Date;

/**
 * 常用字段自动填充器<br />
 * 默认填充策略：如果原来的属性有值则不覆盖,如果手动在这里改为null则不填充
 * 创建时间: 2024-01-15 下午 4:08
 *
 * @author milkbox
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    private Integer getLoginId() {
        try {
            return StpUtil.getLoginIdAsInt();
        } catch (NotLoginException e) { // 未登录
            return null;
        } catch (NotWebContextException e) { // 非web上下文，无法使用sa-token
            return null;
        }
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        // 删除字段
        this.strictInsertFill(metaObject, "deleteFlag",
                () -> CommonDeleteFlagEnum.NOT_DELETE, CommonDeleteFlagEnum.class);
        this.strictInsertFill(metaObject, "createUser", this::getLoginId, Integer.class);
        // 创建时间
        this.strictInsertFill(metaObject, "createTime",
                DateTime::now, Date.class);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updateUser", this::getLoginId, Integer.class);
        // 更新时间
        this.strictUpdateFill(metaObject, "updateTime",
                DateTime::now, Date.class);
    }
}
